using System.Text.RegularExpressions;

namespace CSharpPro._1028;

public class UserServiceimpl : UserService
{
    public List<User> users;

    public void setlist(List<User> users)
    {
        this.users = users;
    }

    public List<User> getlist()
    {
        return users;
    }

    public void login()
    {
        Console.Write("输入用户名");
        string username = Console.ReadLine();
        bool a = controlformatname(username);
        if (!a)
        {
            return;
        }

        bool nameistrue = false;
        foreach (User user in users)
        {
            if (username == user.Name)
            {
                nameistrue = true;
            }
        }

        if (nameistrue == false)
        {
            Console.WriteLine("用户名不存在");
            return;
        }

        Console.Write("输入密码");
        string userpwd = Console.ReadLine();
        bool b = controlformatpwd(userpwd);
        if (!b)
        {
            return;
        }

        foreach (User user in users)
        {
            if (username == user.Name && userpwd != user.Pwd)
            {
                Console.Write("密码错误，登录失败");
                return;
            }
            else if (username == user.Name && userpwd == user.Pwd)
            {
                Console.Write("登录成功，进入首页");
                return;
            }
        }
        
    }

    public void register()
    {
        Console.Write("输入用户名");
        string username = Console.ReadLine();
        bool a = controlformatname(username);
        if (!a)
        {
            return;
        }

        foreach (User user in users)
        {
            if (username == user.Name)
            {
                Console.WriteLine("用户名存在,无法注册");
                return;
            }
        }

        Console.Write("输入密码");
        string userpwd = Console.ReadLine();
        bool b = controlformatpwd(userpwd);
        if (!b)
        {
            return;
        }

        users.Add(new User(username, userpwd));
    }
    
    public bool controlformatname(string username)
    {
        Regex regex = new Regex(@"[a-zA-Z0-9_]{3,15}");
        bool isMatch = regex.IsMatch(username);
        if (!isMatch)
        {
            Console.Write("用户名格式不正确");
            return false;
        }

        return true;
    }

    public bool controlformatpwd(string pwd)
    {
        Regex regex1 = new Regex("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{6,20}$");
        bool isMatch2 = regex1.IsMatch(pwd);
        if (!isMatch2)
        {
            Console.Write("密码格式不正确");
            return false;
        }

        return true;
    }
}